﻿using NHibernate;
using NHibernate.Criterion;
using ProgressTracker.Data.Abstract;
using ProgressTracker.Data.Entities;
using System.Collections.Generic;

namespace ProgressTracker.Data.Concrete
{
    public class TaskRepository : ITaskRepository
    {
        ISession _session;

        public TaskRepository(ISession session)
        {
            _session = session;
        }

        public IEnumerable<Task> GetCurrentTasks(int userId)
        {
            return _session.CreateCriteria<Task>()
                .Add(Restrictions.Eq("User.Id", userId))
                .Add(Restrictions.Eq("Archived", false))
                .List<Task>();
        }

        public Task GetTaskById(int id)
        {
            return _session.Get<Task>(id);
        }

        public void Add(Task task)
        {
            using(var transaction = _session.BeginTransaction())
            {
                _session.Save(task);
                transaction.Commit();
            }
        }

        public void Update(Task task)
        {
            using (var transaction = _session.BeginTransaction())
            {
                _session.Update(task);
                transaction.Commit();
            }
        }

        public void Delete(Task task)
        {
            using (var transaction = _session.BeginTransaction())
            {
                _session.Delete(task);
                transaction.Commit();
            }
        }
    }
}
